/*
 * @Author: yanjikun
 * @Date: 2022-05-19 15:37:54
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-06-16 11:46:12
 * @Description: file content
 */
import TrackerService from '@/utils/socket/tracker'
import { notification } from 'ant-design-vue'
import { defineStore } from 'pinia'
import { AlertOutlined } from '@ant-design/icons-vue'

interface SocketState {
  trackerService: TrackerService | null
  messageData: API.SocketDeviceMessageResult | null
}

export const useSocketStore = defineStore({
  id: 'socket',
  state: (): SocketState => ({
    trackerService: null,
    messageData: null,
  }),
  actions: {
    setTrackerService(trackerService: TrackerService | null) {
      this.trackerService = trackerService
    },
    initSocket() {
      const trackerService = this.trackerService ?? new TrackerService()
      trackerService.connect(this.initSocket).then(() => {
        trackerService.subscribe()
        trackerService.receive().subscribe((activity: API.SocketDeviceMessageResult) => {
          this.sendMessage(activity)
          this.messageData = activity
        })
      })
      !this.trackerService && this.setTrackerService(trackerService as TrackerService)
    },
    closeSocket() {
      this.trackerService?.unsubscribe()
      this.trackerService?.disconnect()
      this.setTrackerService(null)
    },
    sendMessage(data: API.SocketDeviceMessageResult) {
      notification.info({
        message: 'sock消息',
        description: data.msg,
        style: {
          wordBreak: 'break-word',
        },
        icon: <AlertOutlined />,
        top: '32px',
      })
    },
  },
})
